//
//  WxLogin.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/11.
//

import Foundation
import SwiftUI
import LeanCloud

class WxLogin : BaseViewModel, LoginProtocol {
    
    
    let typeKey = LoginType.WX.rawValue
    func doLogin() {
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo"
        req.state = "your_custom_state"
        WXApi.send(req)
    }
    
    func bind() {
        //在代理那边处理
    }
    
    
    func doAuthSuc(code: String) {
        //在代理那边处理
        
    }
    
    func doAuthSuc(access_token: String, openid: String) {
        //无需使用
    }
    
    
    func getAuthInfo(code: String) async throws -> (String, String, UserBean) {
        //获取第三方登陆配置
        let accountBean = try await retry(maxRetries: 5, retryDelayMillis: 200) {
            let query = LCQuery(className: "ThirdAccount")
            return try await LeancloudManager.instance.getFirst(query: query, modeType: ThirdAccountBean.self)
        }
        //获取微信token
        let wxBean = try await retry(maxRetries: 5, retryDelayMillis: 200) {
            return try await TencentNetManager.shared.getWxToken(appid: accountBean?.wxId ?? "", secret: accountBean?.wxSecret ?? "", code: code, grant_type: "authorization_code", modeType: WxToken.self)
        }
        let wxInfo = try await retry(maxRetries: 5, retryDelayMillis: 200) {
            return try await TencentNetManager.shared.getWxInfo(access_token: wxBean.access_token ?? "", openid: wxBean.openid ?? "", modeType: WxUserInfo.self)
        }
        let newUserBean = UserBean()
        newUserBean.name = wxInfo.nickname
        newUserBean.sex = wxInfo.sex
        newUserBean.headUrl = wxInfo.headimgurl
        return (typeKey, wxInfo.openid ?? "",newUserBean)
    }
    
    func getAuthInfo(access_token: String, openid: String) async throws -> (String, String, UserBean) {
        //无需使用
        return ("","", UserBean())
    }
    
    func doLoginAccount(type: String, id: String, newUserBean: UserBean) {
        //在代理那边处理
    }
    
    
}
